﻿using System;
using System.ComponentModel;
using System.Windows;
#if !WinRT
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Interactivity;
using LogoFX.Core;
using EventTrigger = System.Windows.Interactivity.EventTrigger;
#else
using LogoFX.Core;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Interactivity;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Markup;
using Windows.UI.Xaml.Media;
using EventTrigger = Windows.UI.Interactivity.EventTrigger;
using Key = Windows.System.VirtualKey;
#endif


namespace LogoFX.Infra.Interactivity
{
    [Obsolete("Use Microsoft.Expression.Interactivity.Core.DataTrigger if possible")]
    public class ValueNullTrigger
#if WP7
        : BindableTriggerBase<FrameworkElement>
#elif !WinRT
        : TriggerBase<DependencyObject>
#else
        : TriggerBase<FrameworkElement>
#endif
    {
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(object), typeof(ValueNullTrigger), 
            new PropertyMetadata(null, new PropertyChangedCallback(OnSourceChanged)));

        private bool _negate;

#region Properties

        
#if (!WP7)
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
#endif
        public object Source
        {
            get { return GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

#if WP7

        
#if (!WP7)
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
#endif
        public Binding SourceBinding
        {
            get { return GetBinding(SourceProperty); }
            set { SetBinding<object>(SourceProperty, value); }
        }

#endif

        
        public bool Negate
        {
            get { return _negate; }
            set { _negate = value; }
        }

#endregion

#region Handlers

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ValueNullTrigger)d).CompareValue(e.NewValue);
        }

        private void CompareValue(object value)
        {
            if (this.AssociatedObject == null) return;      // this is to ensure with initial/static set properties the trigger isn't invoked

            var _result = (value == null);
            if (Negate) _result = !_result;
            if (_result) base.InvokeActions(value);
        }

#endregion

    }
}
